<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { QForm } from '@meetjs/element-plus-kit'
import AthleteCard from './components/AthleteCard.vue'
import { getPublicityInfoApi } from '@/api/athlete'
import { toViewModelListAsync, type AthleteViewModel } from '@/api/athlete/transformer'
import { searchFormConfig } from './searchConfig'

import type { PublicityQueryParams } from './types'
import zcgs1 from '@/assets/athlete/publicity/zcgs1.svg'
import zcgs2 from '@/assets/athlete/publicity/zcgs2.svg'
import zcgs3 from '@/assets/athlete/publicity/zcgs3.svg'

// 加载状态
const loading = ref(false)

// 统计卡片数据
const statisticCards = ref([
	{
		title: '当月公可公示运动员数',
		value: 0,
		icon: zcgs1
	},
	{
		title: '涉及运动项目',
		value: 0,
		icon: zcgs2
	}
])

const handleCardClick = (card: (typeof statisticCards.value)[number]) => {
	console.log('点击统计卡片：', card.title)
	// TODO: 实际跳转或筛选逻辑
}

const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 2).padStart(2, '0')
const defaultPublicityMonth = `${year}${month}`

// 搜索表单数据
const searchForm = ref<PublicityQueryParams>({
	// 默认查询当前月份的公示数据
	publicityTime: defaultPublicityMonth,
	publicityType: 1
})

// 表单引用
const formRef = ref<InstanceType<typeof QForm>>()

const displayedAthletes = ref<AthleteViewModel[]>([])

// 当前月份标题
const currentMonthTitle = computed(() => {
	const now = new Date()
	const year = now.getFullYear()
	const month = String(now.getMonth() + 1).padStart(2, '0')
	return `${year}年${month}月`
})

/**
 * 获取公示信息
 */
const fetchPublicityInfo = async () => {
	try {
		loading.value = true

		const res = await getPublicityInfoApi(searchForm.value)

		if (res.code === 200 && res.data) {
			// 更新统计卡片数据
			statisticCards.value[0].value = res.data.publicityNumber || 0
			statisticCards.value[1].value = res.data.projectNumber || 0

			//  使用异步转换器将 PublicityData 转换为 AthleteViewModel
			// 会自动加载所有运动员的 personPhoto 文件信息到 personPhotoFile 字段

			const publicityDataList = res.data.publicityDataList || []
			displayedAthletes.value = await toViewModelListAsync(publicityDataList)

			console.log('公示数据加载成功:', {
				统计数据: res.data,
				运动员列表: displayedAthletes.value
			})
		} else {
			ElMessage.error(res.msg || '获取公示信息失败')
		}
	} catch (error) {
		console.error('获取公示信息失败:', error)
		ElMessage.error('获取公示信息失败，请稍后重试')
	} finally {
		loading.value = false
	}
}

/**
 * 搜索处理
 */
const handleSearch = () => {
	// 使用搜索表单数据重新获取
	console.log('搜索参数:', searchForm.value)
	fetchPublicityInfo()
}

/**
 * 重置搜索
 */
const handleReset = () => {
	// 重置表单数据
	searchForm.value = {
		athleteName: '',
		publicityTime: defaultPublicityMonth,
		publicityType: 1,
		sex: undefined,
		projectId: undefined,
		orgId: undefined
	}
	// 重置后重新加载当前月份数据
	fetchPublicityInfo()
}

// 组件挂载时获取数据
onMounted(() => {
	fetchPublicityInfo()
})
</script>

<template>
	<div class="athlete-publicity flex flex-col h-full">
		<!-- 固定区域：统计卡片 -->
		<div class="flex-shrink-0 flex gap-4 mb-4">
			<div
				v-for="card in statisticCards"
				:key="card.title"
				class="flex-1 flex items-center px-7 py-6 gap-5 bg-primary rounded-lg cursor-pointer"
				@click="handleCardClick(card)"
			>
				<!-- 图标区域 -->
				<img
					:src="card.icon"
					alt="icon"
					class="size-10 object-contain"
				/>

				<!-- 数据区域 -->
				<div>
					<div class="text-2xl font-600 text-primary mb-1">{{ card.value }}</div>
					<div class="text-xs text-secondary">{{ card.title }}</div>
				</div>
			</div>
		</div>

		<!-- 固定区域：搜索栏 -->
		<div class="flex-shrink-0 bg-primary rounded-lg p-5 flex gap-12">
			<!-- 左侧表单 -->
			<QForm
				ref="formRef"
				:model="searchForm"
				class="flex-1"
				:form-options="searchFormConfig"
				:gutter="16"
			/>

			<!-- 右侧按钮 -->
			<div class="flex gap-8px shrink-0">
				<el-button
					type="primary"
					@click="handleSearch"
				>
					<i class="i-ep-search mr-4px" />
					查询
				</el-button>
				<el-button @click="handleReset">
					<i class="i-ep-refresh mr-4px" />
					重置
				</el-button>
			</div>
		</div>

		<!-- 可滚动区域：标题栏 + 运动员列表 -->
		<div class="mt-8px flex-1 flex flex-col min-h-0">
			<!-- 固定标题 -->
			<div class="flex-shrink-0 bg-primary px-20px py-20px">
				<h2 class="text-16px font-bold text-primary">{{ currentMonthTitle }} 运动员注册公示名单</h2>
			</div>

			<!-- 运动员列表 - 可滚动区域 -->
			<div
				v-loading="loading"
				class="bg-primary px-20px pb-20px flex-1 overflow-y-auto"
			>
				<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-16px pt-16px">
					<AthleteCard
						v-for="athlete in displayedAthletes"
						:key="athlete.id"
						:athlete="athlete"
					/>
				</div>

				<!-- 空状态 -->
				<div
					v-if="!loading && displayedAthletes.length === 0"
					class="py-40px text-center"
				>
					<div class="text-tertiary text-14px">暂无数据</div>
				</div>
			</div>
		</div>
	</div>
</template>
